<?php
	require("include/includes.php");
	require("include/getIP.php");
	
	//fil d'ariane
	$ariane = array(
		array(
			'href' => "index.php",
			'name' => "Home"
		),
		array(
			'href' => "profile.php",
			'name' => "Profile"
		),
		array(
			'href' => "profile_delete.php",
			'name' => "Remove profile"
		)
	);
	
		
	if(!isset($_SESSION["user"]))
	{
		header('location:index.php');
	}	
	
	if(!isset($_SESSION['password_secrete_field_name']))
	{
		$passwordSecreteFieldName = randomString(10);
		$_SESSION['password_secrete_field_name'] = $passwordSecreteFieldName;
	}
	else
	{
		$passwordSecreteFieldName = $_SESSION['password_secrete_field_name'];
	}
	
	$user = $_SESSION["user"];
	
	
	$valuePassword  	= postOrCustom($passwordSecreteFieldName, '');
	$errors = Array();
	
	/// --- VALIDATION DU FORMULAIRE ---
	if(isset($_POST['submit']))
	{ 
		if(!verifyCsrfToken())
		{
			$errors['csrf'] = 'Security token missing!';
		}
		else // CSRF ok
		{
			if(!empty($valuePassword))
			{
				if(Player::checkLogin($user->getNickname(), $valuePassword))
				{
					/// ACCOUNT REMOVING PROCESS
					$success = $user->desactivate();
					if($success)
					{
						session_destroy();
						unset($user);
						header('location:index.php');
					}
					else
					{
						$errors[] = 'Oops! There was an error! Please report it to the administrator.';
					}
				}
				else
				{
					$errors['password'] = 'You didn\'t type your password correctly';
				}
			}
			else
			{
				$errors['password'] = 'You have to fill in your password in order to remove your account';
			}
		}
	}
	
	$template = $twig->loadTemplate('delete_profile.html');
	$template->display(array(
		'pageTitle' 		=> 'Remove my profile',
		'passwordInputName'	=> $passwordSecreteFieldName,
		'username'			=> $user->getNickname(),
		'errors'			=> $errors,
		'crsfToken' 		=> csrfField()
	));

?>